package com.tothefor.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.tothefor.pojo.entity.Question;
import com.tothefor.pojo.entity.QuestionConnect;
import com.tothefor.resultR.R;
import com.tothefor.service.impl.QuestionConnectServiceImpl;
import com.tothefor.service.impl.QuestionServiceImpl;
import com.tothefor.service.impl.QuestionnaireServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/question")
public class QuestionController {
    @Autowired
    private QuestionServiceImpl QuestionService;
    @Autowired
    private QuestionConnectServiceImpl QuestionConnectService;

    @Autowired
    private QuestionnaireServiceImpl QuestionnaireService;

    @PostMapping("/saveQuestion")
    public R<?> save(@RequestBody Question question){
        List<Question> questionList = QuestionService.list();
        if(questionList.size()==0){
            question.setId(1);
        }else{
            question.setId(questionList.get(questionList.size()-1).getId()+1);
        }
        QuestionService.save(question);
        return R.SUCCESS();
    }

    @PostMapping("/saveConnect")
    public R<?> saveConnect(@RequestBody QuestionConnect questionConnect){
        List<Question> questionList = QuestionService.list();
        List<QuestionConnect> QuestionConnect = QuestionConnectService.list();
        if(QuestionConnect.size()==0){
            questionConnect.setId(1);
        }else{
            questionConnect.setId(QuestionConnect.get(QuestionConnect.size()-1).getId()+1);
        }
        if(questionList!=null&questionList.size()>0){
            questionConnect.setQuestionId(questionList.get(questionList.size()-1).getId()+1);
        }
        QuestionConnectService.save(questionConnect);
        return R.SUCCESS();
    }

    @GetMapping("/showQuestion")
    public R<?> showQuestion(){
        List<Question> questionList = QuestionService.list();
        List<Question> needQuestion = new ArrayList<>();
        List<QuestionConnect> questionConnects = QuestionConnectService.list();
        for(QuestionConnect questionConnect:questionConnects){
            if(questionConnect.getNaireId()==0){
                for(Question question : questionList){
                    if(questionConnect.getQuestionId()==question.getId()){
                        needQuestion.add(question);
                    }/*else if(questionConnect.getQuestionId()+1==question.getId()){
                        questionConnect.setQuestionId(questionConnect.getQuestionId()+1);
                        QuestionConnectService.updateById(questionConnect);
                        needQuestion.add(question);
                    }*/
                }
            }
        }
        return R.SUCCESS(needQuestion);

    }
    @GetMapping("/showQuestionAll")
    public R<?> showQuestionAll(){
        List<Question> questionList = QuestionService.list();
        return R.SUCCESS(questionList);
    }
    @PostMapping("/removeQuestion")
    public R<?> removeQuestion(@RequestBody int id){
        List<Question> questionList = QuestionService.list();
        List<QuestionConnect> questionConnects = QuestionConnectService.list();
        for(QuestionConnect questionConnect:questionConnects){
            if(questionConnect.getQuestionId()==id){
                QuestionConnectService.removeById(questionConnect.getId());
            }
        }
        QuestionService.removeById(id);
        return R.SUCCESS();
    }

    @PostMapping ("/showQuestionByNaireId1")
    public R<?> showQuestionByNaireId1(@RequestBody int id){
        List<QuestionConnect> questionConnects=QuestionConnectService.list();
        List<Question> questionList=QuestionService.list();
        List<Question> newList = new LinkedList<>();
        for (QuestionConnect connect:questionConnects){
            if(connect.getNaireId()==id){
                for(Question question:questionList){
                    if(question.getId()==connect.getQuestionId()&&question.getType().equals("1")){
                        newList.add(questionList.get(questionList.indexOf(question)));
                    }
                }
            }
        }
        return R.SUCCESS(newList);
    }

    @PostMapping ("/showQuestionByNaireId")
    public R<?> showQuestionByNaireId(@RequestBody int id){
        List<QuestionConnect> questionConnects=QuestionConnectService.list();
        List<Question> questionList=QuestionService.list();
        List<Question> newList = new LinkedList<>();
        for (QuestionConnect connect:questionConnects){
            if(connect.getNaireId()==id){
                for(Question question:questionList){
                    if(question.getId()==connect.getQuestionId()){
                        newList.add(questionList.get(questionList.indexOf(question)));
                    }
                }
            }
        }
        return R.SUCCESS(newList);
    }

    @PostMapping ("/showQuestionByNaireId2")
    public R<?> showQuestionByNaireId2(@RequestBody int id){
        List<QuestionConnect> questionConnects=QuestionConnectService.list();
        List<Question> questionList=QuestionService.list();
        List<Question> newList = new LinkedList<>();
        for (QuestionConnect connect:questionConnects){
            if(connect.getNaireId()==id){
                for(Question question:questionList){
                    if(question.getId()==connect.getQuestionId()&&question.getType().equals("2")){
                        newList.add(questionList.get(questionList.indexOf(question)));
                    }
                }
            }
        }
        return R.SUCCESS(newList);
    }

    @PostMapping ("/showQuestionByNaireId3")
    public R<?> showQuestionByNaireId3(@RequestBody int id){
        List<QuestionConnect> questionConnects=QuestionConnectService.list();
        List<Question> questionList=QuestionService.list();
        List<Question> newList = new LinkedList<>();
        for (QuestionConnect connect:questionConnects){
            if(connect.getNaireId()==id){
                for(Question question:questionList){
                    if(question.getId()==connect.getQuestionId()&&question.getType().equals("3")){
                        newList.add(questionList.get(questionList.indexOf(question)));
                    }
                }
            }
        }
        return R.SUCCESS(newList);
    }


    @PostMapping("/import")
    public R imp(MultipartFile file) {
        //System.out.println("==========>>>>><<<<<<>>>>>>+++筋骨肉1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Question> questions = CollUtil.newArrayList();
        List<QuestionConnect> connects = CollUtil.newArrayList();
        List<Question> questionList = QuestionService.list();
        List<QuestionConnect> questionConnectList = QuestionConnectService.list();
        try {

            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);

            List<List<Object>> list = reader.read(1);

            System.out.println(list.size());
            int id=questionList.get(questionList.size()-1).getId()+1;
            int id2=questionConnectList.get(questionConnectList.size()-1).getId()+1;
            for (List<Object> row : list) {
                Question question = new Question();
                question.setId(id);
                question.setName(row.get(0).toString());
                question.setType(row.get(1).toString());
                question.setAnswer1(row.get(2).toString());
                question.setAnswer2(row.get(3).toString());
                question.setAnswer3(row.get(4).toString());
                question.setAnswer4(row.get(5).toString());

                questions.add(question);

                QuestionConnect connect=new QuestionConnect();
                connect.setId(id2);
                connect.setNaireId(0);
                connect.setQuestionId(id);
                connects.add(connect);
                id++;
                id2++;
            }
        }catch (Exception e){
            return R.FAIL();
        }
        boolean isSave = QuestionService.saveBatch(questions);
        QuestionConnectService.saveBatch(connects);
        if(isSave){
            return R.SUCCESS();
        }else{
            return R.FAIL();
        }

    }

    @GetMapping("/exportMB")
    public void exportMB(HttpServletRequest request, HttpServletResponse response) throws Exception{
//        String token = request.getHeader("token");

        List<Map<String, Object>> list = CollUtil.newArrayList();
        Question question=new Question();
        question.setName("这里填写问题名称");
        question.setType("这里填写题目类型,1：单选，2：多选，3：填空");
        question.setAnswer1("选项1");
        question.setAnswer2("选项2");
        question.setAnswer3("选项3");
        question.setAnswer4("选项4");

        Map<String, Object> row1 = new LinkedHashMap<>();
        row1.put("题目名称",question.getName());
        row1.put("题目类型",question.getType());
        row1.put("选项1",question.getAnswer1());
        row1.put("选项2",question.getAnswer2());
        row1.put("选项3",question.getAnswer3());
        row1.put("选项4",question.getAnswer4());

        list.add(row1);


        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("导入模板", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);


    }
    @PostMapping("/getQuestionID")
    public R<?> getQuestionID(@RequestBody int questionnaireID){
        List<QuestionConnect> questionConnects= QuestionConnectService.list();
        List<Object> questionID = new ArrayList<>();
        for(QuestionConnect QuestionConnect:questionConnects){
            if(questionnaireID == QuestionConnect.getNaireId()){
                questionID.add(QuestionConnect.getQuestionId());
            }
        }
        return R.SUCCESS(questionID);
    }

}
